package com.sanchunhui.psc.ui.fragment

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.eightbitlab.rxbus.Bus
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sanchuihun.psc.ui.fragment.BaseMvpFragment
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.ui.adapter.ProjectTeamsAdapter
import com.sanchunhui.psc.event.TeamAllCheckedEvent
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.injection.component.DaggerProjectTeamComponent
import com.sanchunhui.psc.injection.module.ProjectTeamModule
import com.sanchunhui.psc.presenter.ProjectTeamsPresenter
import com.sanchunhui.psc.presenter.view.ProjectTeamsView
import com.sanchunhui.psc.ui.activity.AddTeamActivity
import com.sanchunhui.psc.ui.activity.LoginActivity
import kotlinx.android.synthetic.main.fragment_project_teams.*
import kotlinx.android.synthetic.main.header.*
import org.jetbrains.anko.startActivity
import com.kennyc.view.MultiStateView
import com.sanchunhui.psc.data.protocol.Pagination
import com.sanchunhui.psc.data.protocol.Project
import com.sanchunhui.psc.data.protocol.Team
import com.sanchunhui.psc.event.TeamHandleEvent
import com.sanchunhui.psc.ext.onClick
import com.sanchunhui.psc.ext.startLoading
import com.sanchunhui.psc.ui.activity.SetTeamInfoActivity
import org.json.JSONObject


/**
 * @Author zyx
 * @Date 2021/4/19-18:21
 * @Dscribe 登陆角色为项目组负责人时，显示的小组列表主界面
 */

class ProjectTeamsFragment : BaseMvpFragment<ProjectTeamsPresenter>(), ProjectTeamsView , BGARefreshLayout.BGARefreshLayoutDelegate , View.OnClickListener{


    private lateinit var teamsListAdapter: ProjectTeamsAdapter

    private var mCurrentPage: Int = 1
    private var mMaxPage: Int = 1

    private val STATE_DEFAULT = 0//默认状态
    private val STATE_EDIT = 1//编辑状态
    private var mEditMode = STATE_DEFAULT
    private var editorStatus = false//是否为编辑状态

    private var mListener: OnListFragmentInteractionListener? = null

    private var mTeamList : MutableList<Team> = mutableListOf()

    private lateinit var pagination : Pagination // 分页模型

    private lateinit var projectInfo : Project

    /*
       Dagger注册
    */
    override fun injectComponent() {
        DaggerProjectTeamComponent.builder().activityComponent(mActivityComponent).projectTeamModule(ProjectTeamModule()).build().inject(this)
        mPresenter.mView = this
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater?.inflate(R.layout.fragment_project_teams,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initHeader()
        initObserve()
        initView()
        initRefreshLayout()
    }

    override fun onStart() {
        super.onStart()
        loadProjectInfo()
        loadData()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnListFragmentInteractionListener) {
            mListener = context
        } else {
            throw RuntimeException("$context must implement OnListFragmentInteractionListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onListFragmentInteraction(team:Team)
    }

    /*
        获取项目信息
     */
    fun loadProjectInfo() {
        val user = BaseApplication.mUser
        mPresenter.getProjectInfo(user.token.toString())
    }

    /*
      初始化视图
   */
    private fun initView() {
        mTeamRv.layoutManager = LinearLayoutManager(activity)
        teamsListAdapter = ProjectTeamsAdapter(activity)
        mTeamRv.adapter = teamsListAdapter
        teamsListAdapter.mListener = this.mListener!!
        mMultiStateView.viewState = MultiStateView.ViewState.CONTENT

    }

    /*
       初始化刷新视图
    */
    private fun initRefreshLayout() {
        mRefreshLayout.setDelegate(this)
        val viewHolder = BGANormalRefreshViewHolder(context, true)
        viewHolder.setLoadMoreBackgroundColorRes(R.color.common_bg)
        viewHolder.setRefreshViewBackgroundColorRes(R.color.common_bg)
        mRefreshLayout.setRefreshViewHolder(viewHolder)
    }

    // 初始化header
    private fun initHeader() {

        mAllCheckedCb.visibility = View.GONE
        iv_add.visibility = View.VISIBLE
        tv_edit.visibility = View.VISIBLE
        ll_project_headerTitle.visibility = View.VISIBLE
        lay_project_bottom.visibility = View.VISIBLE

        tv_edit.onClick(this)

        // 项目开工
        tv_project_start.setOnClickListener {
            changeProjectStatus("start")
        }

        // 项目停工
        tv_project_stop.setOnClickListener {
            changeProjectStatus("stop")
        }

        // 项目完工
        tv_project_complete.setOnClickListener {
            changeProjectStatus("complete")
        }

        // 分组开工
        tv_team_start.setOnClickListener {
            changeTeamStatus("start")
        }

        //分组收工
        tv_team_pause.setOnClickListener {
            changeTeamStatus("pause")
        }

        //点击添加按钮
        iv_add.setOnClickListener{
            val intent : Intent = Intent(context, AddTeamActivity::class.java)
            startActivity(intent)
        }

        // 全选按钮事件
        mAllCheckedCb.setOnClickListener {
            for (item in teamsListAdapter.mData) {
                item.isSelected = mAllCheckedCb.isChecked
            }
            teamsListAdapter.notifyDataSetChanged()
        }
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.tv_edit -> { // 编辑
                if (!projectInfo.status.equals("start")) {
                    val toast = Toast.makeText(context, "项目未开工", Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
                } else {
                    updateEditState()
                }
            }
        }
    }

    /*
        项目状态操作
     */
    fun changeProjectStatus(status: String) {
        val user = BaseApplication.mUser
        if (status.equals("start") && projectInfo.status.equals("start")) {
            val toast = Toast.makeText(context, "项目已经开工", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else if (status.equals("stop") && projectInfo.status.equals("stop")) {
            val toast = Toast.makeText(context, "项目已经停工", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else if (status.equals("complete") && projectInfo.status.equals("complete")) {
            val toast = Toast.makeText(context, "项目已经完工", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else {
            var message : String = ""
            var title : String = ""
            if (status.equals("start")) {
                title = String.format(context!!.getString(R.string.open_project))
                message = String.format(context!!.getString(R.string.open_project_message), projectInfo.name)
            } else if (status.equals("stop")) {
                title = String.format(context!!.getString(R.string.stop_project))
                message = String.format(context!!.getString(R.string.stop_project_message), projectInfo.name)
            } else if (status.equals("complete")) {
                title =String.format(context!!.getString(R.string.complete_project))
                message = String.format(context!!.getString(R.string.complete_project_message), projectInfo.name)
            }

            AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                        dialogInterface, i ->  mPresenter.changeProjectInfo(user.token.toString(), status)
                })
                .show()
        }
    }

    /*
        小组状态操作
     */
    fun changeTeamStatus(status:String) {
        val user = BaseApplication.mUser
        var mTeams : MutableList<Team> = mutableListOf()
        for (item in teamsListAdapter.mData) {
            if(item.isSelected) {
                mTeams.add(item)
            }
        }

        var message : String = ""
        var title : String = ""
        var temStatus : String = ""

        if (status.equals("start")) {
            message = "是否允许已选中的小组开工"
            title = String.format(context!!.getString(R.string.open_team))
            temStatus = String.format(context!!.getString(R.string.open))
        } else if (status.equals("pause")) {
            message = "是否允许已选中的小组收工"
            title = String.format(context!!.getString(R.string.pause_team))
            temStatus = String.format(context!!.getString(R.string.pause))
        }
        if (mTeams.size > 0) {
            AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                        dialogInterface, i ->   for (i in mTeams.indices) {
                    var mTeam = mTeams.get(i)
                    mPresenter.changeTeamStatus(mTeam.id, user.token.toString(), status)
                }
                })
                .show()
        } else {
            val toast = Toast.makeText(context, "请选择要${temStatus}的小组", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }

    /*
        更改管理状态
     */
    fun updateEditState() {
        mEditMode = if (mEditMode == STATE_DEFAULT) STATE_EDIT else STATE_DEFAULT
        if (mEditMode == STATE_EDIT) {
            tv_edit.setText("完成")
            lay_team_bottom.setVisibility(View.VISIBLE)
            lay_project_bottom.visibility = View.GONE
            mAllCheckedCb.visibility = View.VISIBLE
            editorStatus = true
        } else {
            tv_edit.setText("管理")
            lay_project_bottom.setVisibility(View.VISIBLE)
            lay_team_bottom.setVisibility(View.GONE)
            mAllCheckedCb.visibility = View.GONE
            mAllCheckedCb.isChecked = false
            editorStatus = false

            setAllItemUnchecked()//取消全选
        }
        teamsListAdapter.setEditMode(mEditMode)
    }

    //取消全部选中
    private fun setAllItemUnchecked() {
        if (teamsListAdapter == null) return
        for (i in mTeamList.indices) {
            mTeamList.get(i).isSelected = false
        }
        teamsListAdapter.notifyDataSetChanged()
    }

    /*
       加载数据
    */
    private fun loadData() {
        val user = BaseApplication.mUser
        mMultiStateView.startLoading()
        mPresenter.getTeamList(user.token.toString())
    }

    /*
       上拉加载更多
    */
    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        return if (mCurrentPage < mMaxPage) {
            mCurrentPage++
            loadData()
            true
        } else {
            false
        }
    }

    /*
       下拉加载第一页
    */
    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        mCurrentPage = 1
        loadData()
    }

    /*
        注册监听
     */
    private fun  initObserve() {
        // 全选
        Bus.observe<TeamAllCheckedEvent>().subscribe {
            run {
                mAllCheckedCb.isChecked = it.isAllChecked
            }
        }
        // 删除
        Bus.observe<TeamHandleEvent>().subscribe {
            run {
                val user = BaseApplication.mUser
                if (it.postion == 0) {
                    val intent : Intent = Intent(context, SetTeamInfoActivity::class.java)
                    intent.putExtra("teamId",it.team.id.toString())
                    startActivity(intent)
                } else if (it.postion == 1) {
                    val message = String.format(context!!.getString(R.string.delete_group_message), it.team.name)
                    AlertDialog.Builder(context)
                        .setTitle(R.string.delete_group_title)
                        .setMessage(message)
                        .setNegativeButton(R.string.cancel, null)
                        .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                            dialogInterface, i ->  mPresenter.changeTeamStatus(it.team.id, user.token.toString(), "delete")
                        })
                        .show()
                }
            }
        }
    }

    /*
        获取项目信息结果
     */
    override fun onProjectInfoResult(result: ResponseInfo) {
        if (result.code == 0) {
            projectInfo = Gson().fromJson(result.data.toString(), Project::class.java)
            tv_project_title.text = projectInfo.name.trim()
            tv_project_count.text = "(${projectInfo.member_cnt})"
            if (projectInfo.status.equals("start")) {
                tv_project_status_start.visibility = View.VISIBLE
                tv_project_status_stop.visibility = View.GONE
                tv_project_status_complete.visibility = View.GONE
            } else if (projectInfo.status.equals("stop")) {
                tv_project_status_start.visibility = View.GONE
                tv_project_status_stop.visibility = View.VISIBLE
                tv_project_status_complete.visibility = View.GONE
            } else if (projectInfo.status.equals("complete")) {
                tv_project_status_start.visibility = View.GONE
                tv_project_status_stop.visibility = View.GONE
                tv_project_status_complete.visibility = View.VISIBLE
            }
        }
    }

    /*
        更改项⽬状态请求结果
     */
    override fun onChangeProjectStatusResult(result: ResponseInfo) {
        if (result.code == 0) {
            val toast = Toast.makeText(context, "操作成功", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
            loadData()
        } else {
            val toast = Toast.makeText(context, "操作失败，有分组在开工状态！", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }

        loadProjectInfo()
    }

    /*
        更改小组状态请求结果
     */
    override fun onChangeTeamStatusResult(result: Boolean) {
        loadData()
    }

    /*
        获取项目下分组列表
     */
    override fun onGetTeamListResult(result: ResponseInfo) {
        mRefreshLayout.endLoadingMore()
        mRefreshLayout.endRefreshing()
        if (result.code == 0) {
            val json = result.data
            parserJson(json.toString())
        } else if (result.code == 401) {
            context!!.startActivity<LoginActivity>()
        }
    }

    override fun onError(text: String) {
        super.onError(text)
        if (mTeamList.size < 0) {
            mMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

    /*
        解析数据
    */
    fun parserJson(json: String) {
        val gson = Gson()
        var jsonObject = JSONObject(json)
        var teams = jsonObject.getString("teams")
        var paginationStr = jsonObject.getString("pagination")
        pagination = Gson().fromJson(paginationStr, Pagination::class.java)
        var temasList : ArrayList<Team> = gson.fromJson(teams, object : TypeToken<List<Team>>() {}.type)

        if (temasList.isNotEmpty()) {
            mTeamList = temasList
            teamsListAdapter.setData(temasList)
            mMultiStateView.viewState = MultiStateView.ViewState.CONTENT
        } else {
            mMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

}